package com.lottery.material.service.portal.article.impl;

import com.alibaba.fastjson.JSONArray;
import com.lottery.material.dao.article.*;
import com.lottery.material.dao.circle.CircleInfoMapper;
import com.lottery.material.dao.conf.VocabularyFilterConfigMapper;
import com.lottery.material.dao.portaluser.PortalUserInfoMapper;
import com.lottery.material.pojo.article.ArticleCompetitionInfo;
import com.lottery.material.pojo.article.ArticleInfo;
import com.lottery.material.pojo.article.ArticlePictureInfo;
import com.lottery.material.pojo.article.ArticleTextInfo;
import com.lottery.material.pojo.circle.CircleInfo;
import com.lottery.material.pojo.conf.VocabularyFilterConfig;
import com.lottery.material.pojo.page.PageData;
import com.lottery.material.pojo.portaluser.PortalUserInfo;
import com.lottery.material.pojocustom.article.ArticleInfoCustom;
import com.lottery.material.service.portal.article.ArticleInfoService;
import com.lottery.material.util.*;
import com.lottery.material.vo.portal.article.ArticleDeletedVo;
import com.lottery.material.vo.portal.article.ArticleInfoListVo;
import com.lottery.material.vo.portal.user.CollectArticleUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author:houjie
 * @Description: 发帖接口实现类
 * @Date:Create in 2019/4/9 15:17
 */
@Service
@Slf4j
public class ArticleInfoServiceImpl  implements ArticleInfoService {

    //当前的项目名称
    @Value("${PROJECT_NAME}")
    private String PROJECT_NAME;

    //当前的模块名称
    @Value("${ARTICLE_INFO_MODULE_NAME}")
    private String ARTICLE_INFO_MODULE_NAME;

    //服务终端
    @Value("${OSS_END_POINT}")
    private String OSS_END_POINT;

    //许可证ID
    @Value("${OSS_ACCESS_KEY_ID}")
    private String OSS_ACCESS_KEY_ID;

    //许可证秘钥
    @Value("${OSS_ACCESS_KEY_SECRET}")
    private String OSS_ACCESS_KEY_SECRET;

    //存储空间名
    @Value("${OSS_BUCKET_NAME}")
    private String OSS_BUCKET_NAME;



    @Autowired
    private ArticleInfoMapper articleInfoMapper;
    @Autowired
    private ArticleActiveInfoMapper articleActiveInfoMapper;
    @Autowired
    private ArticleTextInfoMapper articleTextInfoMapper;
    @Autowired
    private ArticlePictureInfoMapper articlePictureInfoMapper;
    @Autowired
    private ArticleCompetitionInfoMapper articleCompetitionInfoMapper;
    @Autowired
    private VocabularyFilterConfigMapper vocabularyFilterConfigMapper;
    @Autowired
    private CircleInfoMapper circleInfoMapper;
    @Autowired
    private PortalUserInfoMapper portalUserInfoMapper;

    @Override
    public List<CollectArticleUserVo> findCollectArticleByUserIdAndPage(Map<String, Object> paramMap) {
        paramMap.put("indexStart", Const.PORTAL_PAGE*(Integer.parseInt(paramMap.get("page").toString())-1));
        paramMap.put("pageTotal",Const.PORTAL_PAGE);
        return articleInfoMapper.findCollectArticleByUserIdAndPage(paramMap);
    }

    @Override
    public List<VocabularyFilterConfig> findVocabularyFilterConfigList() {
        return vocabularyFilterConfigMapper.findVocabularyFilterConfigList();
    }

    @Override
    public ResponseResult vocabularyFilter(Map<String, String> reqParamMap, List<VocabularyFilterConfig> vocabularyFilterConfigList) {
        String articleTitle = reqParamMap.get("articleTitle");//文章标题
        String freeArticleContents = reqParamMap.get("freeArticleContents");//免费文章内容
        String paidArticleContents = reqParamMap.get("paidArticleContents");//付费文章内容
        for(VocabularyFilterConfig v:vocabularyFilterConfigList){
            if(AssertUtil.isNotEmpty(articleTitle) && articleTitle.contains(v.getVocabulary())){
                return ResponseResult.buildResult(400,"文章标题含有风控词汇！");
            }
            if(AssertUtil.isNotEmpty(freeArticleContents) && freeArticleContents.contains(v.getVocabulary())){
                return ResponseResult.buildResult(400,"免费文章内容含有风控词汇！");
            }
            if(AssertUtil.isNotEmpty(paidArticleContents) && paidArticleContents.contains(v.getVocabulary())){
                return ResponseResult.buildResult(400,"付费文章内容含有风控词汇！");
            }
        }
        return null;
    }

    @Override
    public ResponseResult insertArticleInfo(Map<String, String> reqParamMap, HttpServletRequest request) {
        CircleInfo circleInfo = circleInfoMapper.selectByPrimaryKey(Integer.valueOf(reqParamMap.get("circleId")));
        PortalUserInfo portalUserInfo = portalUserInfoMapper.findByUserId(reqParamMap.get("userId"));
        if(AssertUtil.isEmpty(circleInfo)){
            return ResponseResult.buildResult(400,"圈子id错误！");
        }
        ArticleInfo articleInfo = new ArticleInfo();
        articleInfo.setCreateTime(CalendarUtil.getSystemCurrentDate());//创建时间
        articleInfo.setArticleId(StringUtil.getUUID());
        articleInfo.setIsHot(Integer.valueOf(reqParamMap.get("isHot")));//是否进入热帖
        articleInfo.setIsCharge(Integer.valueOf(reqParamMap.get("isCharge")));//是否收费
        if(AssertUtil.isNotEmpty(reqParamMap.get("chargeAmount"))){
            articleInfo.setChargeAmount(Integer.valueOf(reqParamMap.get("chargeAmount")));//收费金额
        }
        if("2".equals(reqParamMap.get("isHot")) || "2".equals(reqParamMap.get("isCharge"))){//进入热帖或收费文章需要审核
            articleInfo.setArticleState(1);//文章审核状态
        }else{//不需要审核
            articleInfo.setArticleState(3);
            articleInfo.setAuditTime(CalendarUtil.getSystemCurrentDate());
        }
        //收费文章锁定
        if("2".equals(reqParamMap.get("isCharge"))){
            articleInfo.setLockState(1);
        }else{
            articleInfo.setLockState(2);
        }
        articleInfo.setIsDelete(1);
        articleInfo.setCircleId(Integer.valueOf(reqParamMap.get("circleId")));
        articleInfo.setCircleSecondMenuCode(circleInfo.getSubTypeCode());//圈子的二级分类编号
        if(AssertUtil.isNotEmpty(reqParamMap.get("articleTitle"))){//文章标题
            articleInfo.setTitle(reqParamMap.get("articleTitle"));
        }
        articleInfo.setFreeContentOrderRule(reqParamMap.get("freeContentSort"));//免费内容排序规则规则排序

        //文章内容列表
        List<ArticleTextInfo> articleTextList = new ArrayList<ArticleTextInfo>();
        //图片内容列表
        List<ArticlePictureInfo>  articlePictureList = new ArrayList<ArticlePictureInfo>();
        //赛事内容列表
        List<ArticleCompetitionInfo> articleCompetitionList = new ArrayList<ArticleCompetitionInfo>();


        //免费文章内容
        if(AssertUtil.isNotEmpty(reqParamMap.get("freeArticleContents"))){
            JSONArray freeArticleContents =JSONArray.parseArray(reqParamMap.get("freeArticleContents"));//免费内容
            articleInfo.setDefaultContent(freeArticleContents.getString(0));
            for(int i=0;i<freeArticleContents.size();i++){
                ArticleTextInfo articleTextInfo =new ArticleTextInfo();
                articleTextInfo.setArticleId(articleInfo.getArticleId());
                articleTextInfo.setSort(i+1);
                articleTextInfo.setContent(freeArticleContents.getString(i));
                articleTextInfo.setTextChargeType(1);
                articleTextInfo.setCreateTime(CalendarUtil.getSystemCurrentDate());
                articleTextList.add(articleTextInfo);
            }
        }

        //免费图片内容
//        if(AssertUtil.isNotEmpty(reqParamMap.get("freeArticleImages"))){
            //图片是数组的
            /*JSONArray freeArticleImages =JSONArray.parseArray(reqParamMap.get("freeArticleImages"));
            for(int i=0;i<freeArticleImages.size();i++){
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                MultipartFile multipartFile= multipartRequest.getFile(freeArticleImages.getString(i));
                String picUrl=OSSClientUtil.uploadFile(multipartFile,OSS_END_POINT, OSS_ACCESS_KEY_ID,
                        OSS_ACCESS_KEY_SECRET, OSS_BUCKET_NAME, PROJECT_NAME, ARTICLE_INFO_MODULE_NAME);
                String smallPicUrl = OSSClientUtil.resizeUploadFile(multipartFile,OSS_END_POINT, OSS_ACCESS_KEY_ID,
                        OSS_ACCESS_KEY_SECRET, OSS_BUCKET_NAME, PROJECT_NAME, ARTICLE_INFO_MODULE_NAME,60,40);
                ArticlePictureInfo articlePictureInfo =new ArticlePictureInfo();
                articlePictureInfo.setArticleId(articleInfo.getArticleId());
                articlePictureInfo.setPictureChargeType(1);
                articlePictureInfo.setCreateTime(CalendarUtil.getSystemCurrentDate());
                articlePictureInfo.setSort(i+1);
                articlePictureInfo.setOriginalImageUrl(picUrl);
                articlePictureInfo.setThumbnailImageUrl(smallPicUrl);
                articlePictureList.add(articlePictureInfo);
            }*/
            //图片是单个的
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> multipartFiles= multipartRequest.getFiles("pics");
            if(multipartFiles != null && multipartFiles.size() > 0) {
                for (int i = 0; i < multipartFiles.size(); i++) {
                    MultipartFile multipartFile = multipartFiles.get(i);
                    String picUrl = OSSClientUtil.uploadFile(multipartFile, OSS_END_POINT, OSS_ACCESS_KEY_ID,
                            OSS_ACCESS_KEY_SECRET, OSS_BUCKET_NAME, PROJECT_NAME, ARTICLE_INFO_MODULE_NAME);
                    String smallPicUrl = OSSClientUtil.resizeUploadFile(multipartFile, OSS_END_POINT, OSS_ACCESS_KEY_ID,
                            OSS_ACCESS_KEY_SECRET, OSS_BUCKET_NAME, PROJECT_NAME, ARTICLE_INFO_MODULE_NAME, 60, 40);
                    ArticlePictureInfo articlePictureInfo = new ArticlePictureInfo();
                    articlePictureInfo.setArticleId(articleInfo.getArticleId());
                    articlePictureInfo.setPictureChargeType(1);
                    articlePictureInfo.setCreateTime(CalendarUtil.getSystemCurrentDate());
                    articlePictureInfo.setSort(i + 1);
                    articlePictureInfo.setOriginalImageUrl(picUrl);
                    articlePictureInfo.setThumbnailImageUrl(smallPicUrl);
                    articlePictureList.add(articlePictureInfo);
                }
            }

//        }
        //免费赛事内容
        if(AssertUtil.isNotEmpty(reqParamMap.get("freeArticlsCompetitionIds"))){
            JSONArray freeArticlsCompetitionIds =JSONArray.parseArray(reqParamMap.get("freeArticlsCompetitionIds"));
            articleInfo.setDefaultCompetitionId(freeArticlsCompetitionIds.getInteger(0));
            for(int i=0;i<freeArticlsCompetitionIds.size();i++){
                ArticleCompetitionInfo articleCompetitionInfo = new ArticleCompetitionInfo();
                articleCompetitionInfo.setArticleId(articleInfo.getArticleId());
                articleCompetitionInfo.setCompetitionChargeType(1);
                articleCompetitionInfo.setCompetitionId(freeArticlsCompetitionIds.getInteger(i));
                articleCompetitionInfo.setSort(i+1);
                articleCompetitionInfo.setCreateTime(CalendarUtil.getSystemCurrentDate());
                articleCompetitionList.add(articleCompetitionInfo);
            }

        }


        if(AssertUtil.isNotEmpty(reqParamMap.get("paidContentSort"))){
            articleInfo.setChargeContentOrderRule(reqParamMap.get("paidContentSort"));//付费内容排序规则
        }


        //付费文章内容
        if(AssertUtil.isNotEmpty(reqParamMap.get("paidArticleContents"))){
            JSONArray paidArticleContents =JSONArray.parseArray(reqParamMap.get("paidArticleContents"));//付费内容
            for(int i=0;i<paidArticleContents.size();i++){
                ArticleTextInfo articleTextInfo =new ArticleTextInfo();
                articleTextInfo.setArticleId(articleInfo.getArticleId());
                articleTextInfo.setSort(i+1);
                articleTextInfo.setContent(paidArticleContents.getString(i));
                articleTextInfo.setTextChargeType(2);
                articleTextInfo.setCreateTime(CalendarUtil.getSystemCurrentDate());
                articleTextList.add(articleTextInfo);
            }
        }

        //付费赛事内容
        if(AssertUtil.isNotEmpty(reqParamMap.get("paidArticlsCompetitionIds"))){
            JSONArray paidArticlsCompetitionIds =JSONArray.parseArray(reqParamMap.get("paidArticlsCompetitionIds"));
            if(AssertUtil.isEmpty(articleInfo.getDefaultCompetitionId())){
                articleInfo.setDefaultCompetitionId(paidArticlsCompetitionIds.getInteger(0));
            }
            for(int i=0;i<paidArticlsCompetitionIds.size();i++){
                ArticleCompetitionInfo articleCompetitionInfo = new ArticleCompetitionInfo();
                articleCompetitionInfo.setArticleId(articleInfo.getArticleId());
                articleCompetitionInfo.setCompetitionChargeType(1);
                articleCompetitionInfo.setCompetitionId(paidArticlsCompetitionIds.getInteger(i));
                articleCompetitionInfo.setSort(i+1);
                articleCompetitionInfo.setCreateTime(CalendarUtil.getSystemCurrentDate());
                articleCompetitionList.add(articleCompetitionInfo);
            }
        }

        if(AssertUtil.isNotEmpty(reqParamMap.get("paidArticlsCompetitionIds"))|| AssertUtil.isNotEmpty(reqParamMap.get("freeArticlsCompetitionIds"))){//文章赛事id
            articleInfo.setIsExistCompetition(2);
            articleInfo.setIsCompetitionEnd(1);
        }else{
            articleInfo.setIsExistCompetition(1);
        }
        if("-1".equals(reqParamMap.get("publicType"))){//永不
            articleInfo.setIsEndPublic(1);
        }else{
            articleInfo.setIsEndPublic(2);
            if("1".equals(reqParamMap.get("publicType"))){//一天后
                articleInfo.setPublicTime(CalendarUtil.getWantedDate(CalendarUtil.getSystemCurrentDate(),null,1,null,null, null));
            }else if("2".equals(reqParamMap.get("publicType"))){//两天后
                articleInfo.setPublicTime(CalendarUtil.getWantedDate(CalendarUtil.getSystemCurrentDate(),null,2,null,null, null));
            }else if("3".equals(reqParamMap.get("publicType"))){//三天后
                articleInfo.setPublicTime(CalendarUtil.getWantedDate(CalendarUtil.getSystemCurrentDate(),null,3,null,null, null));
            }else if("4".equals(reqParamMap.get("publicType"))){//四天后
                articleInfo.setPublicTime(CalendarUtil.getWantedDate(CalendarUtil.getSystemCurrentDate(),null,4,null,null, null));
            }else if("5".equals(reqParamMap.get("publicType"))){//五天后
                articleInfo.setPublicTime(CalendarUtil.getWantedDate(CalendarUtil.getSystemCurrentDate(),null,5,null,null, null));
            }else if("6".equals(reqParamMap.get("publicType"))){//六天后
                articleInfo.setPublicTime(CalendarUtil.getWantedDate(CalendarUtil.getSystemCurrentDate(),null,6,null,null, null));
            }else{//七天后
                articleInfo.setPublicTime(CalendarUtil.getWantedDate(CalendarUtil.getSystemCurrentDate(),null,7,null,null, null));
            }
        }
        articleInfo.setUpdateTime(CalendarUtil.getSystemCurrentDate());
        articleInfo.setUserId(portalUserInfo.getUserId());
        articleInfo.setNickName(portalUserInfo.getNickName());

        //保存文章主体
        articleActiveInfoMapper.insertArticleInfo(articleInfo);
        articleInfoMapper.insertSelective(articleInfo);
        //保存文字部分
        if(AssertUtil.isNotEmpty(articleTextList) && articleTextList.size()>0){
            articleTextInfoMapper.insertList(articleTextList);
        }
        //保存图片部分
        if(AssertUtil.isNotEmpty(articlePictureList) && articlePictureList.size()>0){
            articlePictureInfoMapper.insertList(articlePictureList);
        }
        //保存赛事部分
        if(AssertUtil.isNotEmpty(articleCompetitionList) && articleCompetitionList.size()>0){
            articleCompetitionInfoMapper.insertList(articleCompetitionList);
        }

        return ResponseResult.buildResult(200,"发帖成功！");
    }

    @Override
    public List<Map<String, Object>> findPurchasedArticleByUserIdAndPage(Map<String, Object> map) {
        map.put("indexStart", Const.PORTAL_PAGE*(Integer.parseInt(map.get("page").toString())-1));
        map.put("pageTotal",Const.PORTAL_PAGE);
        return articleInfoMapper.findPurchasedArticleByUserIdAndPage(map);
    }

    @Override
    public List<ArticleDeletedVo> findDeletedArticleByUserId(Map<String, Object> map) {
        return articleInfoMapper.findDeletedArticleByUserId(map);
    }

    @Override
    public List<ArticleInfo> findTheDayByUserIdAndCircleId(PageData pd) {
        return articleInfoMapper.findTheDayByUserIdAndCircleId(pd);
    }

    @Override
    public List<Map<String,Object>> findByUserIdAndPage(Map<String,Object> map) {
        map.put("indexStart", Const.PORTAL_PAGE*(Integer.parseInt(map.get("page").toString())-1));
        map.put("pageTotal",Const.PORTAL_PAGE);
        return articleInfoMapper.findByUserIdAndPage(map);
    }
    /**
     * description: 根据文章id查询
     * author sunny
     * createDate 2019-04-16 下午 4:24
     * @param articleId
     * @return
     */
    @Override
    public ArticleInfo findByArticleId(String articleId) {
        return articleInfoMapper.findByArticleId(articleId);
    }

    /**
     * description: 根据用户userId及圈子id查询累计发帖量
     * author sunny
     * createDate 2019-04-16 下午 8:13
     * @param userId
     * @param circleId
     * @return
     */
    @Override
    public Integer findCountByUserIdAndCircleId(String userId, String circleId) {
        return articleInfoMapper.findCountByUserIdAndCircleId(userId, circleId);
    }

    /**
     * description: 查询当前比赛下的文章
     * author sunny
     * createDate 2019-04-23 上午 11:31
     * @param paramMap
     * @return
     */
    @Override
    public List<ArticleInfoListVo> findCompetitionArticle(Map<String, Object> paramMap) {
        return articleInfoMapper.findCompetitionArticle(paramMap);
    }

    /**
     * description: 查询当前圈子下的文章
     * author sunny
     * createDate 2019-04-23 下午 2:52
     * @param paramMap
     * @return
     */
    @Override
    public List<ArticleInfoListVo> findCircleArticle(Map<String, Object> paramMap) {
        return articleInfoMapper.findCircleArticle(paramMap);
    }

    /**
     * description: 根据文章id查询详情
     * author sunny
     * createDate 2019-04-23 下午 5:53
     * @param articleId
     * @return
     */
    @Override
    public ArticleInfoCustom findArticleDetailByArticleId(String articleId) {
        return articleInfoMapper.findArticleDetailByArticleId(articleId);
    }

    /**
     * description: 修改文章中所含赛事为结束状态
     * author sunny
     * createDate 2019-04-19 下午 2:55
     * @param articleId
     */
    @Override
    public void updateIsCompetitionEndForTrue(String articleId) {
        articleActiveInfoMapper.updateIsCompetitionEndForTrue(articleId);
        articleInfoMapper.updateIsCompetitionEndForTrue(articleId);
    }

    /**
     * description: 更新文章阅读量
     * author sunny
     * createDate 2019-04-25 下午 3:37
     * @param articleId
     */
    @Override
    public void updateReadTotalByArticleId(String articleId) {
        articleInfoMapper.updateReadTotalByArticleId(articleId);
        articleActiveInfoMapper.updateReadTotalByArticleId(articleId);
    }

    /**
     * description: 更新文章信息
     * author sunny
     * createDate 2019-04-26 下午 4:39
     * @param articleInfo
     */
    @Override
    public void updateArticleInfo(ArticleInfo articleInfo) {
        articleInfoMapper.updateByArticleId(articleInfo);
        articleActiveInfoMapper.updateByArticleId(articleInfo);
    }

    /**
     * description: 根据圈子Id查询文章置顶总数
     * author sunny
     * createDate 2019-04-30 上午 10:08
     * @param circleId
     * @return
     */
    @Override
    public Integer findTopCountByCircleId(Integer circleId) {
        return articleInfoMapper.findTopCountByCircleId(circleId) ;
    }

}
